package org.csu.mybigpro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.mybigpro.common.CommonResponse;
import org.csu.mybigpro.common.ResponseCode;
import org.csu.mybigpro.domain.User;
import org.csu.mybigpro.domain.UserRole;
import org.csu.mybigpro.persistence.UserMapper;
import org.csu.mybigpro.persistence.UserRoleMapper;
import org.csu.mybigpro.service.AuthService;
import org.csu.mybigpro.util.JwtUtil;
import org.csu.mybigpro.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("authService")
public class AuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public CommonResponse<Map<String, Object>> login(String username, String password) {
        // 1. 根据用户名查用户
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("username", username);
        User user = userMapper.selectOne(userQuery);

        if (user == null) {
            return CommonResponse.createForError("用户不存在");
        }

        // 2. 校验密码
        if (!user.getPassword().equals(password)) {
            return CommonResponse.createForError("密码错误");
        }

        // 3. 根据userId查所有角色
        QueryWrapper<UserRole> roleQuery = new QueryWrapper<>();
        roleQuery.eq("user_id", user.getId());
        List<UserRole> roles = userRoleMapper.selectList(roleQuery);

        if (roles == null || roles.isEmpty()) {
            return CommonResponse.createForError("该用户无任何身份");
        }

        // 4. 判断身份优先级（假设管理员优先级最高）
        String roleName = null;
        Long roleId = null;
        for (UserRole ur : roles) {
            if (ur.getRoleId() == 1L) { // 管理员
                roleName = "管理员";
                roleId = 1L;
                break;
            } else if (ur.getRoleId() == 3L) { // 教师
                roleName = "教师";
                roleId = 3L;
            }
        }
        if (roleName == null) {
            return CommonResponse.createForError("该用户身份不支持登录");
        }

        // 5. 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("roleId", roleId);
        String token = jwtUtil.generateToken(user, claims);

        // 6. 清除敏感数据返回
        user.setPassword(null);
        user.setFaceDescriptor(null);

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", user);
        data.put("role", roleName); // 传递身份信息

        return CommonResponse.createForSuccess("登录成功", data);
    }

    @Override
    public Integer getRoleIdByUserId(Long userId) {
        QueryWrapper<UserRole> query = new QueryWrapper<>();
        query.eq("user_id", userId);
        UserRole userRole = userRoleMapper.selectOne(query);
        if (userRole != null) {
            return userRole.getRoleId().intValue();
        }
        return null;
    }

    @Override
    public CommonResponse<User> getCurrentUser() {
        Integer userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return CommonResponse.createForError("无法获取当前用户信息，请重新登录");
        }
        User user = userMapper.selectById(userId);
        if (user == null) {
            return CommonResponse.createForError("用户不存在");
        }
        user.setPassword(null); // 不返回密码
        return CommonResponse.createForSuccess("获取成功", user);
    }

    @Override
    public CommonResponse<?> updateFaceDescriptor(String descriptor) {
        Integer userId = UserContext.getCurrentUserId();
        if (userId == null) {
            return CommonResponse.createForError("无法获取当前用户信息，请重新登录");
        }
        User currentUser = userMapper.selectById(userId);
        if (currentUser == null) {
            return CommonResponse.createForError("用户不存在");
        }
        currentUser.setFaceDescriptor(descriptor);
        userMapper.updateById(currentUser);
        return CommonResponse.createForSuccessMessage("人脸信息更新成功");
    }
    @Override
    public CommonResponse<?> updateUserInfo(User updatedUser) {
        Integer currentUserId = UserContext.getCurrentUserId();
        // 【修复】将 currentUserId 转换为 Long 类型再进行比较
        if (currentUserId == null || !Long.valueOf(currentUserId).equals(updatedUser.getId())) {
            // 防止用户篡改其他用户的信息
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        User existingUser = userMapper.selectById(currentUserId);
        if (existingUser == null) {
            return CommonResponse.createForError("用户不存在");
        }

        // 仅更新允许修改的字段
        existingUser.setName(updatedUser.getName());
        existingUser.setEmail(updatedUser.getEmail());
        existingUser.setPhone(updatedUser.getPhone());
        existingUser.setDepartment(updatedUser.getDepartment());
        // 密码、用户名、人脸数据等不应通过此接口修改

        int rowCount = userMapper.updateById(existingUser);
        if (rowCount > 0) {
            return CommonResponse.createForSuccessMessage("个人信息更新成功");
        }
        return CommonResponse.createForError("个人信息更新失败");
    }

    @Override
    public CommonResponse<String> updateAvatarUrl(Integer userId, String avatarUrl) {
        Integer currentUserId = UserContext.getCurrentUserId();
        if (currentUserId == null || !currentUserId.equals(userId)) {
            return CommonResponse.createForError(ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }

        User currentUser = userMapper.selectById(userId);
        if (currentUser == null) {
            return CommonResponse.createForError("用户不存在");
        }
        currentUser.setAvatarUrl(avatarUrl);
        int rowCount = userMapper.updateById(currentUser);
        if (rowCount > 0) {
            return CommonResponse.createForSuccess("头像更新成功", avatarUrl); // 成功时也返回新的URL
        }
        return CommonResponse.createForError("头像更新失败");
    }
}
